package com.quzhi.sys.controller.orderController;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quzhi.common.Result;
import com.quzhi.common.Utils;
import com.quzhi.common.code.Code;
import com.quzhi.common.code.OrderCode;
import com.quzhi.common.code.UpdateModelCode;
import com.quzhi.sys.dto.OrderAndReceiveGoodsDto;
import com.quzhi.sys.dto.OrderDto;
import com.quzhi.sys.dto.ReceiveGoodsDto;
import com.quzhi.sys.entity.*;
import com.quzhi.sys.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Xibing
 * @since 2024-06-29
 */
@Slf4j
@RestController
@RequestMapping("/sys/order")
public class OrderController {
    @Autowired
    private OrderServiceImpl orderService;

    @Autowired
    private OrderSerialNumberServiceImpl serialNumberService;

    @Autowired
    private OrderRemarkServiceImpl orderRemarkService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserServiceImpl userService;


    @Autowired
    private OrderLogServiceImpl orderLogService;


    @Autowired
    private GoodsSerialNumberServiceImpl goodsSerialNumberService;


    @Autowired
    private ReceiveGoodsServiceImpl receiveGoodsService;


    @Autowired
    private BlacklistServiceImpl blacklistService;


    @Autowired
    private TransferRecordServiceImpl transferRecordService;


    @GetMapping("/list")
    public Result<?> getOrderList(@RequestParam(value = "orderNumber", required = false) String orderNumber,
                                  @RequestParam(value = "phone", required = false) String phone,
                                  @RequestParam(value = "orderByDesc", required = false) String orderByDesc,
                                  @RequestParam(value = "userName", required = false) String userName,
                                  @RequestParam(value = "deliveryDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime deliveryDate,
                                  @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
                                  @RequestParam(value = "createTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime createTime,
                                  @RequestParam(value = "pageNo") Long pageNo,
                                  @RequestParam(value = "pageSize") Long pageSize,
                                  @RequestParam(value = "orderStatus", required = false) String orderStatus) {
        // 判断已标记的订单是否为爱租机订单如果是则更新
        // 判断是否是已标记页面
        if (orderStatus != null) {
            if (orderStatus.equals(Code.YI_BIAO_JI) || orderStatus.equals(Code.AI_ZU_JI)) {
                // 查询所有已标记订单
                LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Order::getOrderStatus, Code.YI_BIAO_JI);

                List<Order> list = orderService.list(wrapper);

                for (Order o : list) {
                    if (o.getOrderNumber() != null) {
                        // 判断前两个字符是否是 "SA"
                        if (o.getOrderNumber().length() >= 2 && o.getOrderNumber().startsWith("SA")) {
                            // 更新订单状态
                            o.setOrderStatus(Code.AI_ZU_JI);
                            orderService.updateById(o);
                        }
                    }
                }
            }
        }


        // 未标记订单和登记订单对撞
        if (orderStatus != null) {
            // 判断请求的页面是不是标记页面
            if (orderStatus.equals(Code.WEI_BIAO_JI) || orderStatus.equals(Code.YI_BIAO_JI) || orderStatus.equals(Code.AI_ZU_JI)) {
                // 获取全部未标记和已标记的订单
                LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
                orderLambdaQueryWrapper.eq(Order::getOrderStatus, Code.WEI_BIAO_JI);

                List<Order> list = orderService.list(orderLambdaQueryWrapper);

                List<OrderRemark> orderRemarks = orderRemarkService.list();


                for (Order o : list) {
                    for (OrderRemark orderRemark : orderRemarks) {
                        if (o.getPhone().equals(orderRemark.getPhone())) {
                            // 未登记的订单备注
                            orderRemark.setStatus(true);
                            orderRemarkService.updateById(orderRemark);
                            break;
                        }
                    }
                }
            }
        }


        // 更新已逾期订单
        if (orderStatus != null) {
            // 判断请求页面是不是已逾期页面
            if (orderStatus.equals(Code.YI_YU_QI) || orderStatus.equals(Code.DAI_FA_YI_FA_HUO) || orderStatus.equals(Code.YI_FA_HUO) || orderStatus.equals(Code.DAI_FA_YI_YU_QI)) {
                // 查询所有已发货订单
                LambdaQueryWrapper<Order> YQWrapper = new LambdaQueryWrapper<>();
                YQWrapper.eq(Order::getOrderStatus, Code.YI_FA_HUO).or().eq(Order::getOrderStatus, Code.DAI_FA_YI_FA_HUO);
                YQWrapper.isNotNull(Order::getStartTime);
                YQWrapper.isNotNull(Order::getEndTime);
                List<Order> list = orderService.list(YQWrapper);


                // 判断订单是否已逾期
                for (Order o : list) {
                    try {
                        if (o.getEndTime() != null) {
                            // 预估结束日期小于当前日期则是已逾期
                            LocalDateTime yuqi = LocalDateTime.of(o.getEndTime().getYear(), o.getEndTime().getMonth(), o.getEndTime().getDayOfMonth() + Code.ONE, 0, 0, 0);
                            if (yuqi.isBefore(LocalDateTime.now())) {
                                if (o.getOrderStatus().equals(Code.DAI_FA_YI_FA_HUO)) {
                                    // 更新状态为已逾期
                                    o.setOrderStatus(Code.DAI_FA_YI_YU_QI);
                                } else {
                                    // 更新状态为已逾期
                                    o.setOrderStatus(Code.YI_YU_QI);
                                }

                                orderService.updateById(o);
                            }
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        log.error("订单更新逾期出错," + o.toString());
                    }
                }


            }
        }


        Page<Order> infoPage = new Page<>(pageNo, pageSize);
        Page<OrderDto> OrderDtoPage = new Page<>();

        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        // 获取当前的日期和时间
        LocalDateTime now = LocalDateTime.now();


        if (deliveryDate != null) {
            LocalDate currentDate = now.toLocalDate();
            // 如果是今天则查询今天和今天之前的所有订单
            if (currentDate.equals(deliveryDate.toLocalDate())) {
                // 查询今天和今天之前的并且查询日期为空的
                wrapper.le(Order::getDeliveryDate, deliveryDate);
            } else {
                // 查询 指定日期的订单
                wrapper.eq(Order::getDeliveryDate, deliveryDate); // eq等于
            }

        }

        if (endTime != null) {
            // 如果是今天则查询今天和今天之前的所有订单
            // 查询该日志之前的并且查询日期为空的
            wrapper.le(Order::getEndTime, endTime);
        }
        if (createTime != null) {
            // 如果是今天则查询今天和今天之前的所有订单
            // 查询该日志之前的并且查询日期为空的
            wrapper.eq(Order::getCreateTime, createTime);
        }

        // 通过用户名或手机号码模糊查询
        wrapper.like(StringUtils.hasLength(orderNumber), Order::getOrderNumber, orderNumber);
        wrapper.like(StringUtils.hasLength(phone), Order::getPhone, phone);
        wrapper.like(StringUtils.hasLength(userName), Order::getUserName, userName);
        if (orderStatus != null) wrapper.eq(Order::getOrderStatus, orderStatus);

        if (orderByDesc != null) {
            // 排序
            switch (orderByDesc) {
                case "平台":
                    wrapper.orderByAsc(Order::getOrderPlatform);
                    break;
                case "发货日":
                    wrapper.orderByAsc(Order::getDeliveryDate);
                    break;
                case "型号":
                    wrapper.orderByAsc(Order::getTradeName);
                    break;
                case "起租日":
                    wrapper.orderByAsc(Order::getStartTime);
                    break;
                case "下单日":
                    wrapper.orderByAsc(Order::getCreateTime);
                    break;
            }
        } else {
            wrapper.orderByDesc(Order::getCreateTime);
        }


        orderService.page(infoPage, wrapper);

        // 对象拷贝
        BeanUtils.copyProperties(infoPage, OrderDtoPage, "records");

        List<Order> records = infoPage.getRecords();
        List<OrderDto> orders = new ArrayList<>();

        for (Order record : records) {
            OrderDto orderDto = new OrderDto();

            BeanUtils.copyProperties(record, orderDto);

            LambdaQueryWrapper<OrderSerialNumber> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderSerialNumber::getOrderId, orderDto.getId());
            // 更具订单ID查询序列号表
            List<OrderSerialNumber> OrderSerialNumbers = serialNumberService.list(lambdaQueryWrapper);

            // 更具订单ID查询日志
            LambdaQueryWrapper<OrderLog> orderLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLogLambdaQueryWrapper.eq(OrderLog::getOrderId, record.getId());
            orderLogLambdaQueryWrapper.orderByDesc(OrderLog::getCreateTime); // 降序
            List<OrderLog> list = orderLogService.list(orderLogLambdaQueryWrapper);

            orderDto.setOrderLogs(list);
            orderDto.setSerialNumbers(OrderSerialNumbers);
            orders.add(orderDto);
        }


        Map<String, Object> data = new HashMap<>();
        data.put("rows", orders);
        data.put("total", infoPage.getTotal());

        return Result.success(data);


    }

    /**
     * 更具Id查询订单
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Order> getOrderById(@PathVariable("id") String id) {
        OrderDto orderDto = new OrderDto();

        Order order = orderService.getById(id);
        BeanUtils.copyProperties(order, orderDto);

        LambdaQueryWrapper<OrderSerialNumber> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderSerialNumber::getOrderId, orderDto.getId());

        List<OrderSerialNumber> list = serialNumberService.list(wrapper);

        orderDto.setSerialNumbers(list);

        return Result.success(orderDto);
    }


    /**
     * 查寄回查询订单
     *
     * @param phone
     * @param username
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getSendBackOrderList")
    public Result<?> getSendBackOrderList(@RequestParam(value = "phone", required = false) String phone,
                                          @RequestParam(value = "username", required = false) String username,
                                          @RequestParam(value = "orderNumber", required = false) String orderNumber,
                                          @RequestParam(value = "pageNo") Long pageNo,
                                          @RequestParam(value = "pageSize") Long pageSize) {

        // 查询所有订单状态为（已发货，代发已发货，已逾期，代发已逾期，坏账）的和满足传入参数的订单
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(phone), Order::getPhone, phone);
        wrapper.eq(StringUtils.hasLength(orderNumber), Order::getOrderNumber, orderNumber);
        wrapper.eq(StringUtils.hasLength(username), Order::getUserName, username);


        wrapper.in(Order::getOrderStatus, Code.YI_FA_HUO, Code.DAI_FA_YI_FA_HUO, Code.YI_YU_QI, Code.DAI_FA_YI_YU_QI, Code.HUAI_ZHANG);
        // 分页查询
        Page<Order> infoPage = new Page<>(pageNo, pageSize);


        orderService.page(infoPage, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("rows", infoPage.getRecords());
        data.put("total", infoPage.getTotal());

        return Result.success(data);
    }


    /**
     * 根据修改模式修改
     *
     * @param order
     * @param model 修改模式
     * @return
     */
    @PutMapping
    public Result<?> updateOrder(@RequestBody OrderDto order, @RequestParam(value = "model") String model, HttpServletRequest request) {

        // 获取当前用户信息
        String token = request.getHeader("qz-Token");
        User userinfoForBack = userService.getUserinfoForBack(token);


        // 结束日不能小于起租日
        if (order.getStartTime() != null && order.getEndTime() != null) {
            if (order.getEndTime().isBefore(order.getStartTime()))
                return Result.fail(Code.UPDATE_FAIL_CODE, "结束日期，不能早于起租日期");
        }


        // 更具起租日和时效计算发货日
        if (order.getAgeing() != null && order.getStartTime() != null) {
            order.setDeliveryDate(order.getStartTime().minusDays(order.getAgeing()));
        }


        Order updateOrder = new Order();
        BeanUtils.copyProperties(order, updateOrder);

        Order dataBaseOrderById = orderService.getById(order.getId());
        // 先到数据库中查询数据，然后根据模式修改数据
        // 如果是逾期订单则更具起租日和结束日结束按租期时间
        if (order.getOrderStatus().equals(Code.DAI_FA_YI_YU_QI) || order.getOrderStatus().equals(Code.YI_YU_QI)) {
            // 更具起租期和天数计算结束的时间
            if (Objects.equals(order.getDuration(), dataBaseOrderById.getDuration())) { // 如果没有修改天数则判断
                if (order.getStartTime() != null && order.getDuration() != null && order.getDuration() != null) {
                    // 计算两个日期之间的天数差
                    long daysBetween = ChronoUnit.DAYS.between(order.getStartTime(), order.getEndTime());

                    order.setDuration((int) daysBetween + Code.ONE);

                    // 修改天数后判断是否逾期
                    LocalDateTime yuqi = LocalDateTime.of(order.getEndTime().getYear(), order.getEndTime().getMonth(), order.getEndTime().getDayOfMonth() + Code.ONE, 0, 0, 0);

                    if (yuqi.isAfter(LocalDateTime.now())) {
                        if (order.getOrderStatus().equals(Code.DAI_FA_YI_YU_QI)) {
                            order.setOrderStatus(Code.DAI_FA_YI_FA_HUO);
                        } else {
                            order.setOrderStatus(Code.YI_FA_HUO);
                        }
                    }
                }
            } else {
                // 修改租期，更具起租日和天数计算结束时间
                order.setEndTime(order.getStartTime().plusDays(order.getDuration() - Code.ONE));
            }

        } else {
            // 更具起租期和天数计算结束的时间
            if (order.getStartTime() != null && order.getDuration() != null) {
                order.setEndTime(order.getStartTime().plusDays(order.getDuration() - Code.ONE));
            }
        }


        if (userinfoForBack != null) {
            // 每次更新都生成一次更新日志
            switch (model) {
                case UpdateModelCode.ORDER_INFO:
                    // 修改订单消息
                    dataBaseOrderById.setCreditRating(order.getCreditRating());
                    dataBaseOrderById.setOrderPlatform(order.getOrderPlatform());
                    dataBaseOrderById.setOrderNumber(order.getOrderNumber());
                    dataBaseOrderById.setTradeName(order.getTradeName());
                    dataBaseOrderById.setSetMeal(order.getSetMeal());
                    dataBaseOrderById.setAttachment(order.getAttachment());
                    // 修改订单信息不添加到日志
                    break;
                case UpdateModelCode.SendInfo:
                    // 修改发货信息
                    dataBaseOrderById.setAgeing(order.getAgeing()); // 时效
                    dataBaseOrderById.setDeliveryDate(order.getDeliveryDate()); // 发货日
                    dataBaseOrderById.setFreight(order.getFreight()); // 运费
                    //  修改运单号
                    dataBaseOrderById.setTrackingNumber(order.getTrackingNumber());
                    dataBaseOrderById.setReceiptNumber(order.getReceiptNumber());
                    dataBaseOrderById.setGetReceiptNumber(order.getGetReceiptNumber());

                    orderLogService.AddSystemLog(dataBaseOrderById.getId(), "修改发货信息", userinfoForBack.getUsername());
                    break;
                case UpdateModelCode.RemarkInfo:
                    // 备注信息
                    dataBaseOrderById.setRemark(order.getRemark());
                    orderLogService.AddSystemLog(dataBaseOrderById.getId(), "修改备注信息:" + order.getRemark(), userinfoForBack.getUsername());
                    break;
                case UpdateModelCode.RentTimeInfo:
                    // 租期信息
                    dataBaseOrderById.setStartTime(order.getStartTime());
                    dataBaseOrderById.setEndTime(order.getEndTime());
                    dataBaseOrderById.setDuration(order.getDuration());
                    dataBaseOrderById.setMoney(order.getMoney());

                    // 如果是逾期订单判断是否续租
                    if (dataBaseOrderById.getOrderStatus().equals(Code.DAI_FA_YI_YU_QI) || dataBaseOrderById.getOrderStatus().equals(Code.YI_YU_QI)) {
                        // 获取当前天的系统时间
                        LocalDateTime now = LocalDateTime.now();
                        if (dataBaseOrderById.getEndTime().isAfter(now)) {
                            // 续租订单

                            // 更新订单状态
                            if (dataBaseOrderById.getOrderStatus().equals(Code.DAI_FA_YI_YU_QI)) {
                                // 代发续租
                                dataBaseOrderById.setOrderStatus(Code.DAI_FA_YI_FA_HUO);

                            } else {
                                dataBaseOrderById.setOrderStatus(Code.YI_FA_HUO);
                            }

                            // 添加续租日志
                            orderLogService.AddSystemLogExit(dataBaseOrderById.getId(), "已续租", userinfoForBack.getUsername());
                        }
                    }

                    orderLogService.AddSystemLog(dataBaseOrderById.getId(), "修改租期信息", userinfoForBack.getUsername());
                    break;
                case UpdateModelCode.UserInfo:
                    // 修改用户信息
                    dataBaseOrderById.setUserName(order.getUserName());
                    dataBaseOrderById.setPhone(order.getPhone());
                    dataBaseOrderById.setAddress(order.getAddress());
                    orderLogService.AddSystemLog(dataBaseOrderById.getId(), "修改用户信息", userinfoForBack.getUsername());
                    // 获取黑名单用户是黑名单就添加到日志中
                    blacklistService.selectBlackListUser(dataBaseOrderById, token);
                    break;
            }

        } else {
            return Result.fail(Code.UPDATE_FAIL_CODE, "用户信息错误");
        }


        // 设置更新时间
        dataBaseOrderById.setUpdateTime(LocalDateTime.now());
        orderService.updateOrderById(dataBaseOrderById);

        return Result.success("更新成功");
    }


    /**
     * 修改运单号
     *
     * @param
     * @return
     */
    @PutMapping("/updateTrackingNumber/{id}")
    public Result<?> updateTrackingNumber(@PathVariable("id") String id, @RequestBody Map<String, String> trackingNumber) {

        Order updateOrder = orderService.getById(id);
        if (trackingNumber.get("trackingNumber") == null) {
            // 修改寄回单号
            updateOrder.setReceiptNumber(trackingNumber.get("receiptNumber"));
        } else {
            // 修改寄出单号
            updateOrder.setTrackingNumber(trackingNumber.get("trackingNumber"));
        }

        orderService.updateById(updateOrder);

        return Result.success("修改成功");
    }

    /**
     * 查寄回
     *
     * @param
     * @return
     */
    @PutMapping("/updateReceiptNumber/{id}")
    public Result<?> updateReceiptNumber(@PathVariable("id") String id, @RequestBody Order order) {

        Order updateOrder = orderService.getById(id);


        // 更新寄回单号
        updateOrder.setReceiptNumber(order.getReceiptNumber());


        // 更新预计寄回时间
        updateOrder.setGetReceiptDate(order.getGetReceiptDate());

        orderService.updateById(updateOrder);

        return Result.success("修改成功");
    }

    /**
     * 更具id修改订单状态
     *
     * @param id
     * @param UpdateModelAndStatus {model:修改状态的模式, status:修改模式}
     * @return
     */
    @PutMapping("/updateStatus/{id}")
    public Result<?> updateOrderStatus(@PathVariable("id") String id, @RequestBody Map<String, Object> UpdateModelAndStatus, HttpServletRequest request) {

        // 获取当前用户信息
        String token = request.getHeader("qz-Token");
        User userinfoForBack = userService.getUserinfoForBack(token);

        // 根据Id查询订单
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(Order::getId, id);
        Order order = orderService.getOne(orderLambdaQueryWrapper);
        // 判断修改状态
        String model = (String) UpdateModelAndStatus.get(UpdateModelCode.Model);

        // 修改状态的类型
        String status = (String) UpdateModelAndStatus.get(UpdateModelCode.Status);

        // 修改订单状态

        String rwaData = "";
        switch (model) {
            case UpdateModelCode.OrderStatus:
                // 获取订单上次修改时间 小于2秒内则不能修改
                // 待定

                // 如果是将订单状态更新为取消或者待取消，判断库存状态，如果为已减库存，则不能修改
                if (status.equals(Code.DAI_QU_XIAO) || status.equals(Code.QU_XIAO)) {
                    if (order.getStockStatus().equals(Code.YI_JIAN_KU_CUN)) {
                        return Result.fail(Code.UPDATE_FAIL_CODE, "需要先把库存加回来哈");
                    }
                }

                // 修改状态前判断是否能修改
                if (status.equals(Code.DAI_FA_HUO)) { // 修改订单状态为待发货
                    if (order.getAddressStatus().equals(Code.DI_ZHI_XU_HES_SHI)) {
                        return Result.fail(Code.UPDATE_FAIL_CODE, "该订单地址状态异常");
                    }
                    if (order.getDebitStatus().equals(Code.WEI_KOU_KUAN)) {
                        return Result.fail(Code.UPDATE_FAIL_CODE, "该订单未扣款");
                    }
                    if (order.getStockStatus().equals(Code.WEI_JIAN_KU_CUN)) {
                        return Result.fail(Code.UPDATE_FAIL_CODE, "该订单未减库存");
                    }
                    if (order.getStockStatus().equals(Code.MEI_YOU_KU_CUN)) {
                        return Result.fail(Code.UPDATE_FAIL_CODE, "该订单没有库存");
                    }
                }

                if (status.equals(Code.YI_FA_HUO)) {
                    if (order.getTrackingNumber() == null) {
                        return Result.fail(Code.UPDATE_FAIL_CODE, "未输入发出单号");
                    }
                    // 检测序列号是否出库（如果是代发的则不需要检测）
                    if (order.getOrderStatus().equals(Code.DAI_FA_YI_JI_HUI)) {
                        // 直接修改状态
                        status = Code.DAI_FA_YI_FA_HUO;
                        order.setOrderStatus(status);
                    } else {
                        LambdaQueryWrapper<OrderSerialNumber> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                        lambdaQueryWrapper.eq(OrderSerialNumber::getOrderId, order.getId());
                        List<OrderSerialNumber> list = serialNumberService.list(lambdaQueryWrapper);
                        for (OrderSerialNumber orderSerialNumber : list) {
                            if (orderSerialNumber.getStatus().equals(Code.DAI_CHU_KU)) {
                                return Result.fail(Code.UPDATE_FAIL_CODE, order.getOrderNumber() + "序列号待出库");
                            }
                        }
                    }

                }
                if (status.equals(Code.YI_JI_HUI)) {
                    if (order.getReceiptNumber() == null) {
                        String receiptNumber = (String) UpdateModelAndStatus.get("receiptNumber");
                        String getReceiptDate = (String) UpdateModelAndStatus.get("getReceiptDate");

                        if (receiptNumber == null) return Result.fail(Code.UPDATE_FAIL_CODE, "未输入寄回单号");


                        // 设置寄回单号
                        order.setReceiptNumber(receiptNumber);
                        // 设置寄回时间
                        order.setGetReceiptDate(Utils.convertToLocalDateTimeToDate(getReceiptDate));
                    }

                }

                rwaData = "{'orderStatus':'" + order.getOrderStatus() + "'}";
                // 判断订单是不是代发的
                // 判断订单是不是代发的
                if ((order.getOrderStatus().equals(Code.YI_FA_HUO) || order.getOrderStatus().equals(Code.DAI_FA_YI_FA_HUO)) && status.equals(Code.YI_JI_HUI)) {
                    if (order.getOrderStatus().equals(Code.YI_FA_HUO)) {
                        order.setOrderStatus(status);
                    } else {
                        order.setOrderStatus(Code.DAI_FA_YI_JI_HUI);
                    }
                } else {
                    order.setOrderStatus(status);
                    orderLogService.AddSystemLogCopyRawData(order.getId(), "修改订单状态：" + status, userinfoForBack.getUsername(), rwaData);
                }


                break;
            case UpdateModelCode.DebitStatus:

                rwaData = "{'debitStatus':'" + order.getDebitStatus() + "'}";
                // 扣款状态
                order.setDebitStatus(status);
                orderLogService.AddSystemLogCopyRawData(order.getId(), "修改扣款状态：" + status, userinfoForBack.getUsername(), rwaData);

                break;
            case UpdateModelCode.StockStatus:
                // 库存状态
                rwaData = "{'stockStatus':'" + order.getStockStatus() + "'}";
                order.setStockStatus(status);
                orderLogService.AddSystemLogCopyRawData(order.getId(), "修改库存状态：" + status, userinfoForBack.getUsername(), rwaData);
                break;
            case UpdateModelCode.AddressStatus:
                rwaData = "{'addressStatus':'" + order.getAddressStatus() + "'}";
                // 地址状态
                order.setAddressStatus(status);
                orderLogService.AddSystemLogCopyRawData(order.getId(), "修改地址状态：" + status, userinfoForBack.getUsername(), rwaData);
                break;
        }


        // 修改订单
        orderService.updateById(order);

        return Result.success("订单状态修改成功");
    }


    // 更新寄回状态
    @PutMapping("/receiptStatus/{id}")
    public Result<?> updateReceiptStatus(@PathVariable("id") String id) {
        // 更新寄回状态
        Order getOrderById = orderService.getById(id);
        // 判断是否填写寄回单号
        if (getOrderById.getReceiptNumber() == null || getOrderById.getReceiptNumber().equals(""))
            return Result.fail(Code.UPDATE_FAIL_CODE, "请填写寄回单号");

        // 更新状态为已寄回 判断是不是代发的
        if (getOrderById.getOrderStatus().equals(Code.DAI_FA_YI_FA_HUO) || getOrderById.getOrderStatus().equals(Code.DAI_FA_YI_YU_QI)) {
            getOrderById.setOrderStatus(Code.DAI_FA_YI_JI_HUI);
        } else if (getOrderById.getOrderStatus().equals(Code.YI_FA_HUO) || getOrderById.getOrderStatus().equals(Code.YI_YU_QI)) {
            getOrderById.setOrderStatus(Code.YI_JI_HUI);
        } else {
            getOrderById.setOrderStatus(Code.YI_JI_HUI);
        }

        orderService.updateById(getOrderById);

        return Result.success("更新成功");
    }


    @PostMapping
    public Result<?> addOrder(@RequestBody Order order, HttpServletRequest request) {

        String Message = "";

        // 设置订单ID
        order.setId(UUID.randomUUID().toString());

        // 获取当前用户信息
        String token = request.getHeader("qz-Token");
        User userinfoForBack = userService.getUserinfoForBack(token);

        // 获取黑名单用户是黑名单就添加到日志中
        blacklistService.selectBlackListUser(order, token);


        // 更具订单号,用户名，手机号，地址查询是否重复
        LambdaQueryWrapper<Order> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StringUtils.hasLength(order.getOrderNumber()), Order::getOrderNumber, order.getOrderNumber());


        List<Order> orderListForNumber = orderService.list(lambdaQueryWrapper);

        // 订单编号重复重复（可能是补发订单8）
        if (orderListForNumber.size() != 0) {
            // 添加日志(添加订单的日志)

            int index = 0;

            // 所有收货信息重复的订单(查询的订单状态不能是已发货，已寄回， 已完结， 已取消， 待取消， 代发已发货， 代发已寄回， 已签收， 已完结， 代发已完结)
            orderLogService.AddUserLog(order.getId(), OrderCode.ORDER_NUMBER_EXIST, userinfoForBack.getUsername()); // 新增订单日志

            List<Order> tempOrder = new ArrayList<>();

            for (Order number : orderListForNumber) {
                // 如果重复的订单的状态是
                // 添加日志(添加订单的日志)
                if (number.getOrderStatus().equals(Code.YI_FA_HUO) || number.getOrderStatus().equals(Code.YI_JI_HUI) || number.getOrderStatus().equals(Code.DAI_QU_XIAO) || number.getOrderStatus().equals(Code.QU_XIAO) || number.getOrderStatus().equals(Code.DAI_FA_YI_FA_HUO) || number.getOrderStatus().equals(Code.DAI_FA_YI_JI_HUI) || number.getOrderStatus().equals(Code.YI_QIAN_SHOU) || number.getOrderStatus().equals(Code.YI_WAN_JIE) || number.getOrderStatus().equals(Code.DAI_FA_YI_WAN_JIE)) {
                    tempOrder.add(number);
                }

            }


            // 删除不需要添加重复日志的订单
            for (Order temp : tempOrder) {
                orderListForNumber.remove(temp);
            }

            for (Order info : orderListForNumber) {
                // 添加日志(添加订单的日志)
                orderLogService.AddUserLog(info.getId(), OrderCode.ORDER_NUMBER_EXIST, userinfoForBack.getUsername()); // 新增订单日志
            }

            if (orderListForNumber.size() > 0) {
                Message += order.getOrderNumber() + ",订单编号重复";

            }
        }


        // 客户信息重复
        LambdaQueryWrapper<Order> UserInfo = new LambdaQueryWrapper<>();
        UserInfo.eq(StringUtils.hasLength(order.getPhone()), Order::getPhone, order.getPhone());

        List<Order> UserInfoList = orderService.list(UserInfo);
        if (UserInfoList.size() != 0) {
            // 检测是否重复 如果有重复则添加到日志订单日志中

            // 所有收货信息重复的订单(查询的订单状态不能是已发货，已寄回， 已完结， 已取消， 待取消， 代发已发货， 代发已寄回， 已签收， 已完结， 代发已完结)

            // 添加日志(添加订单的日志)
            orderLogService.AddUserLog(order.getId(), OrderCode.USER_INFO_EXIST, userinfoForBack.getUsername());

            List<Order> tempOrder = new ArrayList<>();

            for (Order number : UserInfoList) {
                if (number.getOrderStatus().equals(Code.YI_FA_HUO) || number.getOrderStatus().equals(Code.YI_JI_HUI) || number.getOrderStatus().equals(Code.DAI_QU_XIAO) || number.getOrderStatus().equals(Code.QU_XIAO) || number.getOrderStatus().equals(Code.DAI_FA_YI_FA_HUO) || number.getOrderStatus().equals(Code.DAI_FA_YI_JI_HUI) || number.getOrderStatus().equals(Code.YI_QIAN_SHOU) || number.getOrderStatus().equals(Code.YI_WAN_JIE) || number.getOrderStatus().equals(Code.DAI_FA_YI_WAN_JIE)) {
                    tempOrder.add(number);

                }
            }

            // 删除不需要添加重复日志的订单
            for (Order temp : tempOrder) {
                UserInfoList.remove(temp);
            }

            for (Order info : UserInfoList) {
                // 添加日志(添加订单的日志)
                orderLogService.AddUserLog(info.getId(), OrderCode.USER_INFO_EXIST, userinfoForBack.getUsername()); // 新增订单日志
            }

            if (UserInfoList.size() > 0) {
                if (Message.equals("")) {
                    Message += order.getPhone() + ",客户信息重复";
                } else {
                    Message += ",客户信息重复";
                }
            }
        }

        // 添加导入日志
        orderLogService.AddSystemLog(order.getId(), "新增订单", userinfoForBack.getUsername());

        if (Message.equals("")) {
            return orderService.addOrder(order);
        } else {
            orderService.addOrder(order);
            return Result.fail(Code.ADD_ORDER_FAIL, Message);
        }

    }


    // 发货

    /**
     * @param product {id:订单ID，serialNumber:序列号（多个序列号/隔开），trackingNumber:寄出单号}
     * @return
     */
    @PostMapping("/sendProduct")
    public Result<?> sendProduct(@RequestBody Map<String, Object> product) {
        String id = (String) product.get("id");

        // 根据Id查询订单
        Order order = orderService.getById(id);
        String serialNumber = (String) product.get("serialNumber");
        // 分割序列号
        String[] serialNumbers = serialNumber.split("/");

        for (String number : serialNumbers) {
            // 添加序列号
            String s = serialNumberService.addSerialNumber(number, id, Code.DING_DAN, Code.DAI_CHU_KU);
            if (s.equals("该序列号已绑定订单")) return Result.fail(Code.UPDATE_FAIL_CODE, s);
        }


        String trackingNumber = (String) product.get("trackingNumber");
        order.setTrackingNumber(trackingNumber);

        // 如果是代发则设置为代发已发货
        if (order.getOrderStatus().equals(Code.DAI_FA)) {
            order.setOrderStatus(Code.DAI_FA_YI_FA_HUO);
        } else {
            order.setOrderStatus(Code.YI_FA_HUO);
        }

        // 更新订单
        orderService.updateById(order);

        return Result.success("发货成功");
    }


    @DeleteMapping("/{id}")
    public Result<?> deleteOrderById(@PathVariable("id") String id) {
        // 有重复订单编号，更新订单表查询订单
        Order orderById = orderService.getById(id);

        // 删除重复订单的日志
        // 查询该订单的所有日志判断是否有重复订单信息
        LambdaQueryWrapper<OrderLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderLog::getOrderId, id);
        List<OrderLog> orderLogs = orderLogService.list(wrapper);
        for (OrderLog orderLog : orderLogs) {
            // 订单编号重复
            if (orderLog.getLog().equals(OrderCode.ORDER_NUMBER_EXIST)) {
                // 查询重复订单的所有日志

                // 有重复订单编号，更新订单表查询订单
                LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
                orderLambdaQueryWrapper.eq(Order::getOrderNumber, orderById.getOrderNumber()); // 原订单

                List<Order> list = orderService.list(orderLambdaQueryWrapper);

                if (list.size() > 2) break;
                // 如果只有一条就删除这条订单的日志和重复订单的日志
                // 删除订单编号重复日志
                for (Order order : list) {
                    LambdaQueryWrapper<OrderLog> logLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    logLambdaQueryWrapper.eq(OrderLog::getOrderId, order.getId());
                    logLambdaQueryWrapper.eq(OrderLog::getLog, OrderCode.ORDER_NUMBER_EXIST);
                    orderLogService.remove(logLambdaQueryWrapper); // 删除日志
                }
            }

            if (orderLog.getLog().equals(OrderCode.USER_INFO_EXIST)) {
                // 查询当前订单
                // 收货信息重复


                // 所有收货信息重复的订单(查询的订单状态不能是已发货，已寄回， 已完结， 已取消， 待取消， 代发已发货， 代发已寄回， 已签收， 已完结， 代发已完结)
                LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
                orderLambdaQueryWrapper.eq(Order::getPhone, orderById.getPhone());


                List<Order> list = orderService.list(orderLambdaQueryWrapper);
                log.error(list.size() + "");
                log.error(list.toString());

                if (list.size() > 2) break;

                // 删除订单编号重复日志
                for (Order order : list) {
                    LambdaQueryWrapper<OrderLog> logLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    logLambdaQueryWrapper.eq(OrderLog::getOrderId, order.getId());
                    logLambdaQueryWrapper.eq(OrderLog::getLog, OrderCode.USER_INFO_EXIST);
                    orderLogService.remove(logLambdaQueryWrapper); // 删除日志
                }

            }
        }

        // 删除这条订单的所有日志

        LambdaQueryWrapper<OrderLog> orderLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLogLambdaQueryWrapper.eq(OrderLog::getOrderId, id);
        orderLogService.remove(orderLogLambdaQueryWrapper);

        // 查询该订单是否有订单标号重复的订单
        orderService.removeById(id);

        return Result.success("订单删除成功");
    }

    @DeleteMapping("/ids")
    public Result<?> deleteOrderById(@RequestBody List<String> ids) {

        // 先删除日志
        // 更具id查询订单
        for (String id : ids) {
            // 有重复订单编号，更新订单表查询订单
            Order orderById = orderService.getById(id);

            // 删除重复订单的日志
            // 查询该订单的所有日志判断是否有重复订单信息
            LambdaQueryWrapper<OrderLog> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderLog::getOrderId, id);
            List<OrderLog> orderLogs = orderLogService.list(wrapper);
            for (OrderLog orderLog : orderLogs) {
                // 订单编号重复
                if (orderLog.getLog().equals(OrderCode.ORDER_NUMBER_EXIST)) {
                    // 查询重复订单的所有日志

                    // 有重复订单编号，更新订单表查询订单
                    LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    orderLambdaQueryWrapper.eq(Order::getOrderNumber, orderById.getOrderNumber()); // 原订单

                    List<Order> list = orderService.list(orderLambdaQueryWrapper);

                    if (list.size() > 2) break;
                    // 如果只有一条就删除这条订单的日志和重复订单的日志
                    // 删除订单编号重复日志
                    for (Order order : list) {
                        LambdaQueryWrapper<OrderLog> logLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        logLambdaQueryWrapper.eq(OrderLog::getOrderId, order.getId());
                        logLambdaQueryWrapper.eq(OrderLog::getLog, OrderCode.ORDER_NUMBER_EXIST);
                        orderLogService.remove(logLambdaQueryWrapper); // 删除日志
                    }
                }

                if (orderLog.getLog().equals(OrderCode.USER_INFO_EXIST)) {
                    // 查询当前订单
                    // 收货信息重复


                    // 所有收货信息重复的订单(查询的订单状态不能是已发货，已寄回， 已完结， 已取消， 待取消， 代发已发货， 代发已寄回， 已签收， 已完结， 代发已完结)
                    LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    orderLambdaQueryWrapper.eq(Order::getPhone, orderById.getPhone());


                    List<Order> list = orderService.list(orderLambdaQueryWrapper);
                    log.error(list.size() + "");
                    log.error(list.toString());

                    if (list.size() > 2) break;

                    // 删除订单编号重复日志
                    for (Order order : list) {
                        LambdaQueryWrapper<OrderLog> logLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        logLambdaQueryWrapper.eq(OrderLog::getOrderId, order.getId());
                        logLambdaQueryWrapper.eq(OrderLog::getLog, OrderCode.USER_INFO_EXIST);
                        orderLogService.remove(logLambdaQueryWrapper); // 删除日志
                    }

                }
            }

            // 删除这条订单的所有日志

            LambdaQueryWrapper<OrderLog> orderLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLogLambdaQueryWrapper.eq(OrderLog::getOrderId, id);
            orderLogService.remove(orderLogLambdaQueryWrapper);
        }

        // 更具传递的ID批量删除
        orderService.removeByIds(ids);

        // 删除重复订单的日志
        return Result.success("删除成功");
    }


    /**
     * 批量导出数据
     */
    @GetMapping("/export")
    public void exportData(@RequestParam(value = "startTime") String startTime, @RequestParam(value = "endTime") String endTime,
                           @RequestParam(value = "orderStatus") String orderStatus, HttpServletResponse response) throws IOException {

        // 转换格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 解析日期字符串为 LocalDate
        LocalDate startTimeOfDate = LocalDate.parse(startTime, formatter);
        LocalDate endTimeOfDate = LocalDate.parse(endTime, formatter);

        // 转换为 LocalDateTime，并将时间部分设为 00:00:00
        LocalDateTime startTimeOfDateTime = startTimeOfDate.atStartOfDay();
        LocalDateTime endTimeOfDateTime = endTimeOfDate.atStartOfDay();


        ExcelWriter writer = ExcelUtil.getWriter(true);

        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        // 导出满足条件的日期
        wrapper.between(Order::getStartTime, startTimeOfDateTime, endTimeOfDateTime); // 大于


        // 将逗号分隔的状态列表转换为 List
        List<String> statusArray = Arrays.stream(orderStatus.split(","))
                .map(String::trim)
                .collect(Collectors.toList());


        wrapper.in(Order::getOrderStatus, statusArray);

        // 执行查询

        List<Order> orders = orderService.list(wrapper);

        List<ExportOrder> eOrder = new ArrayList<>();

        for (Order order : orders) {
            ExportOrder exportOrder = new ExportOrder();


            exportOrder.setCreditRating(order.getCreditRating());
            exportOrder.setOrderPlatform(order.getOrderPlatform());
            exportOrder.setDeliveryDate(order.getDeliveryDate());
            exportOrder.setFreight(order.getFreight());
            exportOrder.setRemark(order.getRemark());
            exportOrder.setTradeName(order.getTradeName());
            exportOrder.setSetMeal(order.getSetMeal());
            exportOrder.setStartTime(order.getStartTime());
            exportOrder.setEndTime(order.getEndTime());
            exportOrder.setDuration(order.getDuration());
            exportOrder.setMoney(order.getMoney());
            exportOrder.setAttachment(order.getAttachment());
            exportOrder.setUserName(order.getUserName());
            exportOrder.setPhone(order.getPhone());
            exportOrder.setAddress(order.getAddress());
            exportOrder.setOrderNumber(order.getOrderNumber());
            exportOrder.setOrderDate(order.getCreateTime());
            exportOrder.setStatus(order.getOrderStatus());

            eOrder.add(exportOrder);
        }


        writer.write(eOrder, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("订单表" + LocalDateTime.now().toString(), "utf-8") + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream, true);

        outputStream.flush();
        writer.close();
        outputStream.close();

    }

    /**
     * 批量导入订单
     */
    @PostMapping("/import")
    public Result<?> importData(MultipartFile file) throws IOException {

        // 导入Excel表格
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<Order> orders = reader.readAll(Order.class);

            for (Order order : orders) {
                // 更具发货时间计算时效
                if (order.getDeliveryDate() != null && order.getStartTime() != null) {
                    if (order.getDeliveryDate().isBefore(order.getStartTime())) {
                        // 计算两天的之间的时间
                        long daysBetween = ChronoUnit.DAYS.between(order.getDeliveryDate(), order.getStartTime());
                        order.setAgeing((int) daysBetween);
                    }
                }
            }

            // 查询所有 已标记，未标记，爱租机，订单处理的订单有没有重复的
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getOrderStatus, Code.WEI_BIAO_JI).or().eq(Order::getOrderStatus, Code.YI_BIAO_JI).or().eq(Order::getOrderStatus, Code.AI_ZU_JI).or().eq(Order::getOrderStatus, Code.DING_DIAN_CHU_LI);

            List<Order> list = orderService.list(wrapper);

            List<Order> copyCFData = new ArrayList<>();

            // 添加重复的订单
            for (Order order : list) {
                for (Order o : orders) {
                    if (o.getOrderNumber() != null && order.getOrderNumber() != null) {
                        if (order.getOrderNumber().equals(o.getOrderNumber())) {
                            copyCFData.add(o);
                            break;
                        }
                    }
                }
            }

            // 返回失败的订单
            if (copyCFData.size() > 0) {
                for (Order copyCFDatum : copyCFData) {
                    orders.remove(copyCFDatum);
                }
            }

            // 重复数据
            Map<String, Object> data = new HashMap<>();
            data.put("data", orders);
            data.put("ExistData", copyCFData);

            return Result.success(data);

        } catch (Exception e) {
            log.info(e.toString());
            return Result.fail(Code.UPDATE_FAIL_CODE, "导入失败，请检测导入数据的格式");
        }
    }

    @PostMapping("/addOrders")
    public Result<?> addOrders(@RequestBody List<Order> orders, HttpServletRequest request) {

        for (Order order : orders) {
            // 设置订单ID
            order.setId(UUID.randomUUID().toString());

            // 获取当前用户信息
            String token = request.getHeader("qz-Token");
            User userinfoForBack = userService.getUserinfoForBack(token);

            // 获取黑名单用户是黑名单就添加到日志中
            blacklistService.selectBlackListUser(order, token);


            // 更具订单号,用户名，手机号，地址查询是否重复
            LambdaQueryWrapper<Order> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(StringUtils.hasLength(order.getOrderNumber()), Order::getOrderNumber, order.getOrderNumber());


            List<Order> orderListForNumber = orderService.list(lambdaQueryWrapper);

            // 订单编号重复重复（可能是补发订单8）
            if (orderListForNumber.size() != 0) {
                // 添加日志(添加订单的日志)


                // 所有收货信息重复的订单(查询的订单状态不能是已发货，已寄回， 已完结， 已取消， 待取消， 代发已发货， 代发已寄回， 已签收， 已完结， 代发已完结)
                orderLogService.AddUserLog(order.getId(), OrderCode.ORDER_NUMBER_EXIST, userinfoForBack.getUsername()); // 新增订单日志

                List<Order> tempOrder = new ArrayList<>();

                for (Order number : orderListForNumber) {
                    // 如果重复的订单的状态是
                    // 添加日志(添加订单的日志)
                    if (number.getOrderStatus().equals(Code.YI_FA_HUO) || number.getOrderStatus().equals(Code.YI_JI_HUI) || number.getOrderStatus().equals(Code.DAI_QU_XIAO) || number.getOrderStatus().equals(Code.QU_XIAO) || number.getOrderStatus().equals(Code.DAI_FA_YI_FA_HUO) || number.getOrderStatus().equals(Code.DAI_FA_YI_JI_HUI) || number.getOrderStatus().equals(Code.YI_QIAN_SHOU) || number.getOrderStatus().equals(Code.YI_WAN_JIE) || number.getOrderStatus().equals(Code.DAI_FA_YI_WAN_JIE)) {
                        tempOrder.add(number);
                    }

                }


                // 删除不需要添加重复日志的订单
                for (Order temp : tempOrder) {
                    orderListForNumber.remove(temp);
                }

                for (Order info : orderListForNumber) {
                    // 添加日志(添加订单的日志)
                    orderLogService.AddUserLog(info.getId(), OrderCode.ORDER_NUMBER_EXIST, userinfoForBack.getUsername()); // 新增订单日志
                }


            }


            // 客户信息重复
            LambdaQueryWrapper<Order> UserInfo = new LambdaQueryWrapper<>();
            UserInfo.eq(StringUtils.hasLength(order.getPhone()), Order::getPhone, order.getPhone());

            List<Order> UserInfoList = orderService.list(UserInfo);
            if (UserInfoList.size() != 0) {
                // 检测是否重复 如果有重复则添加到日志订单日志中

                // 所有收货信息重复的订单(查询的订单状态不能是已发货，已寄回， 已完结， 已取消， 待取消， 代发已发货， 代发已寄回， 已签收， 已完结， 代发已完结)

                // 添加日志(添加订单的日志)
                orderLogService.AddUserLog(order.getId(), OrderCode.USER_INFO_EXIST, userinfoForBack.getUsername());

                List<Order> tempOrder = new ArrayList<>();

                for (Order number : UserInfoList) {
                    if (number.getOrderStatus().equals(Code.YI_FA_HUO) || number.getOrderStatus().equals(Code.YI_JI_HUI) || number.getOrderStatus().equals(Code.DAI_QU_XIAO) || number.getOrderStatus().equals(Code.QU_XIAO) || number.getOrderStatus().equals(Code.DAI_FA_YI_FA_HUO) || number.getOrderStatus().equals(Code.DAI_FA_YI_JI_HUI) || number.getOrderStatus().equals(Code.YI_QIAN_SHOU) || number.getOrderStatus().equals(Code.YI_WAN_JIE) || number.getOrderStatus().equals(Code.DAI_FA_YI_WAN_JIE)) {
                        tempOrder.add(number);

                    }
                }

                // 删除不需要添加重复日志的订单
                for (Order temp : tempOrder) {
                    UserInfoList.remove(temp);
                }

                for (Order info : UserInfoList) {
                    // 添加日志(添加订单的日志)
                    orderLogService.AddUserLog(info.getId(), OrderCode.USER_INFO_EXIST, userinfoForBack.getUsername()); // 新增订单日志
                }


            }

            // 添加导入日志
            orderLogService.AddSystemLog(order.getId(), "新增订单", userinfoForBack.getUsername());


            orderService.addOrder(order);
        }

        return Result.success("添加成功");
    }

    // 批量修改定制状态
    @PutMapping("/ids")
    public Result<?> setOrderStatusByIds(@RequestBody List<String> ids, @RequestParam(value = "statusCode") String statusCode, HttpServletRequest request) {

        try {
            String token = request.getHeader("qz-Token");
            return orderService.updateOrderStatusByIds(ids, statusCode, token);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.fail(Code.FAIL_CODE, "批量更新状态失败");
        }
    }

    // 批量更新库存状态订单状态
    @PutMapping("/updateStockStatus")
    public Result<?> updateOrderStatusByIds(@RequestBody List<String> ids, @RequestParam(value = "statusCode") String statusCode, HttpServletRequest request) {

        try {
            String token = request.getHeader("qz-Token");
            orderService.updateOrderStockStatusByIds(ids, statusCode, token);
            return Result.success("更新成功");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return Result.fail(Code.FAIL_CODE, "批量更新状态失败");
        }

    }

    /**
     * 批量导出数据
     */
    @GetMapping("/exportSendOrder")
    public void exportSendOrderData(HttpServletResponse response, @RequestParam String token, @RequestParam String ids) throws IOException {
        // 是否登录
        if (redisTemplate.opsForValue().get(token) == null) return;
        List<Order> orders = new ArrayList<>();
        if (ids == null) {
            return;
        } else {
            // 更具id查询所有选中的订单
            String[] orderIds = ids.split("~");
            for (String orderId : orderIds) {
                // 查询数据库
                Order byId = orderService.getById(orderId);
                orders.add(byId);
            }
        }

        ExcelWriter writer = ExcelUtil.getWriter(true);


        List<SendOrder> sendOrders = new ArrayList<>();

        for (Order order : orders) {
            SendOrder sendOrder = new SendOrder();
            // 设置用户订单号
            sendOrder.setOrderId(null);

            // 设置姓名
            sendOrder.setUserName(order.getUserName());
            // 设置手机号码
            sendOrder.setPhone(order.getPhone());
            // 设置客户收货信息
            sendOrder.setAddress(order.getAddress());

            // 设置物品(获取终点的4个字符)
            if (order.getTradeName().length() > 6) {
                sendOrder.setArticle(order.getTradeName().substring(order.getTradeName().length() / 2 - 3, order.getTradeName().length() - 1));
            } else {
                sendOrder.setArticle(order.getTradeName());
            }

            // 设置备注
            sendOrder.setFreight(order.getFreight());

            if (order.getFreight() == null) {
                sendOrder.setMoney("到付现结");
            } else {
                // 设置邮寄方式
                switch (order.getFreight()) {
                    case Code.JI_FU:
                    case Code.BAO_YOU:
                        sendOrder.setMoney("寄付现结");
                        break;
                    case Code.TE_KUAI_JI_FU:
                        sendOrder.setMoney("寄付现结");
                        break;
                    case Code.TE_KUAI_DAO_FU:
                        sendOrder.setMoney("到付现结");
                        break;
                    default:
                        sendOrder.setMoney("到付现结");
                        break;
                }

            }

            if (order.getFreight() == null) {
                sendOrder.setByPost("顺丰标快");
            } else if (order.getFreight().equals(Code.JI_FU) || order.getFreight().equals(Code.BAO_YOU) || order.getFreight().equals(Code.DAO_FU)) {
                sendOrder.setByPost("顺丰标快");
            } else {
                sendOrder.setByPost("顺丰特快");
            }


            // 设置密钥
            if (!order.getAddressStatus().equals(Code.ZHENG_CHANG)) {
                sendOrder.setKey("是");
            } else {
                sendOrder.setKey("否");
            }

            // 设置配件一
            sendOrder.setTradeName(order.getTradeName());

            // 设置配件二
            sendOrder.setSetMeal(order.getSetMeal());

            sendOrders.add(sendOrder);
        }


        writer.write(sendOrders, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("发货表" + (LocalDate.now().toString()), "utf-8") + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream, true);
        outputStream.flush();
        writer.close();
        outputStream.close();


    }


    /**
     * 批量序列号数据
     */
    @GetMapping("/exportSerialNumber")
    public void exportSerialNumber(HttpServletResponse response, @RequestParam String token, @RequestParam String ids) throws IOException {
        // 是否登录
        List<Order> orders = new ArrayList<>();
        if (redisTemplate.opsForValue().get(token) == null) return;
        if (ids == null) {
            return;
        } else {

            // 更具id查询所有选中的订单
            String[] orderIds = ids.split("~");
            for (String orderId : orderIds) {
                // 查询数据库
                Order byId = orderService.getById(orderId);
                orders.add(byId);
            }
        }

        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 写入表格中国

        List<ExportOrderAndSerialNumber> sendOrders = new ArrayList<>();

        for (Order order : orders) {
            ExportOrderAndSerialNumber exportOrderAndSerialNumber = new ExportOrderAndSerialNumber();
            exportOrderAndSerialNumber.setId(order.getId());
            exportOrderAndSerialNumber.setTradeName(order.getTradeName());
            exportOrderAndSerialNumber.setSetMeal(order.getSetMeal());
            exportOrderAndSerialNumber.setAttachment(order.getAttachment());
            exportOrderAndSerialNumber.setSerialNumberOne(null);
            exportOrderAndSerialNumber.setSerialNumberTwo(null);
            exportOrderAndSerialNumber.setUserName(order.getUserName());
            exportOrderAndSerialNumber.setPhone(order.getPhone());
            exportOrderAndSerialNumber.setAddress(order.getAddress());
            exportOrderAndSerialNumber.setTrackingNumber(order.getTrackingNumber());
            exportOrderAndSerialNumber.setOperator(order.getOperator());
            sendOrders.add(exportOrderAndSerialNumber);
        }

        writer.write(sendOrders, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("序列号表" + (LocalDate.now()), "utf-8") + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream, true);
        outputStream.flush();
        writer.close();
        outputStream.close();


    }

    /**
     * 批量导入序列号
     */
    @PostMapping("/importOrderAndSerialNumber")
    public Result<?> importOrderAndSerialNumber(MultipartFile file) throws IOException {

        // 是否登录
        // 写入数据库
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<ExportOrderAndSerialNumber> orders = reader.readAll(ExportOrderAndSerialNumber.class);
            // 更具Id查询所有数据
            for (ExportOrderAndSerialNumber order : orders) {
                // 查询订单
                Order byId = orderService.getById(order.getId());

                // 写入序列号
                if (order.getSerialNumberOne() != null) {
                    serialNumberService.save(Utils.importOrderSerialNumber(order, order.getSerialNumberOne()));
                }
                if (order.getSerialNumberTwo() != null) {
                    serialNumberService.save(Utils.importOrderSerialNumber(order, order.getSerialNumberTwo()));
                }

                // 写入运单号，和配件
                byId.setTrackingNumber(byId.getTrackingNumber() + order.getTrackingNumber());
                // 配件
                byId.setAttachment(order.getAttachment());

                // 更新订单
                orderService.updateById(byId);
            }

        } catch (Exception e) {
            log.error(e.toString());
            return Result.fail(20002, "导入失败，请检测导入数据的格式");
        }
        return Result.success("导入成功");
    }


    /**
     * 获取寄回的订单
     * return:[{receiveGoodsId：签收单号Id, oddNumber:签收单号, serialNumber:[序列号...], Order:订单编号}....]
     */
    @GetMapping("/getSendBackOrder")
    public Result<?> getSendBackOrder() {
        /**
         *  更具所有未入库的寄回设备的序列号查询订单，查询的订单状态有（已发货，已寄回，已逾期，坏账）
         *  如果没有查询到则返回签收序列号，和运单号
         *  判断寄回信息，是否缺配件，损坏，如果有则将添加到日志中，再更新订单签收单号，将状态更新为已签收
         *  如果没有更新订单签收单号，更新订单状态为已签收
         */
        // 获取所有待入库的收货序列号
        List<GoodsSerialNumber> goodsSerialNumberList = goodsSerialNumberService.getGoodsSerialNumberList(Code.DAI_RU_KU);

        // 所有未入库的运单号和序列号
        List<ReceiveGoodsDto> needGoodsRecordDtoList = receiveGoodsService.getNeedGoodsRecordDtoList(goodsSerialNumberList);


        // 查询已出库的订单序列号和订单号
        // 先查询所有已出库，已寄回，已逾期，坏账的订单
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.eq(Order::getOrderStatus, Code.YI_FA_HUO).or().eq(Order::getOrderStatus, Code.YI_JI_HUI).or().eq(Order::getOrderStatus, Code.YI_YU_QI).or().eq(Order::getOrderStatus, Code.HUAI_ZHANG);
        List<Order> orders = orderService.list(orderLambdaQueryWrapper);
        // 所有满足条件的订单
        List<OrderDto> orderDtoList = serialNumberService.getOrderDtoList(orders);

        // 所有寄回签收的订单和寄回信息
        List<OrderAndReceiveGoodsDto> orderAndReceiveGoodsDtos = new ArrayList<>();

        for (ReceiveGoodsDto receiveGoodsDto : needGoodsRecordDtoList) {
            // 先用寄回单号判断，如果没有机会单号就用序列号判断
            for (OrderDto orderDto : orderDtoList) {

                // 寄回单号判断
                if (receiveGoodsDto.getOddNumber().equals(orderDto.getReceiptNumber())) {
                    // 如果机会单号相同就添加新会信息
                    OrderAndReceiveGoodsDto orderAndReceiveGoodsDto = new OrderAndReceiveGoodsDto();
                    // 复制订单信息
                    BeanUtils.copyProperties(orderDto, orderAndReceiveGoodsDto);

                    // 寄回信息包含序列号
                    orderAndReceiveGoodsDto.setReceiveGoodsDto(receiveGoodsDto);


                    orderAndReceiveGoodsDtos.add(orderAndReceiveGoodsDto);
                } else {
                    // 更具序列号判断
                    List<GoodsSerialNumber> goodsSerialNumbers = receiveGoodsDto.getGoodsSerialNumbers();
                    for (GoodsSerialNumber goodsSerialNumber : goodsSerialNumbers) {
                        boolean flag = false; // 判断是否有，如果有直接结束循环
                        List<OrderSerialNumber> serialNumbers = orderDto.getSerialNumbers();
                        for (OrderSerialNumber serialNumber : serialNumbers) {
                            if (goodsSerialNumber.getSerialNumber().equals(serialNumber.getSerialNumber())) {
                                // 如果序列号相同则是客户寄回的
                                // 如果机会单号相同就添加新会信息
                                OrderAndReceiveGoodsDto orderAndReceiveGoodsDto = new OrderAndReceiveGoodsDto();
                                // 复制订单信息
                                BeanUtils.copyProperties(orderDto, orderAndReceiveGoodsDto);

                                // 寄回信息包含序列号
                                orderAndReceiveGoodsDto.setReceiveGoodsDto(receiveGoodsDto);

                                orderAndReceiveGoodsDtos.add(orderAndReceiveGoodsDto);
                                flag = true;
                                break;
                            }
                        }
                        if (flag) {
                            break;
                        }
                    }
                }
            }
        }


        return Result.success(orderAndReceiveGoodsDtos);
    }


    /**
     * 签收订单
     */
    @PostMapping("/receiveOrder")
    public Result<?> ReceiveOrder(@RequestBody Map<String, String> receiveData, HttpServletRequest request) {
        User userinfoForBack = userService.getUserinfoForBack(request.getHeader("qz-Token"));

        String orderId = receiveData.get("orderId");
        String receiveGoodsId = receiveData.get("receiveGoodsId");

        // 查询订单
        Order order = orderService.getById(orderId);

        // 查询收货信息
        ReceiveGoods receiveGoods = receiveGoodsService.getById(receiveGoodsId);


        // 添加收货运单号
        order.setGetReceiptNumber(receiveGoods.getOddNumber());
        // 添加日志
        if (receiveGoods.getInfo() != null) {
            if (!receiveGoods.getInfo().equals("")) {
                // 设备状态日志
                orderLogService.AddUserLog(orderId, receiveGoods.getInfo(), userinfoForBack.getUsername());
                orderLogService.AddUserLog(orderId, Code.XU_SHOU_HOU, userinfoForBack.getUsername());
            }

        }

        if (receiveGoods.getRemark() != null) {
            if (!receiveGoods.getRemark().equals("")) {
                // 设备状态日志
                orderLogService.AddUserLog(orderId, "收货备注：" + receiveGoods.getRemark(), userinfoForBack.getUsername());
            }
        }

        //


        // 设置状态为已签收
        order.setOrderStatus(Code.YI_QIAN_SHOU);
        // 更新订单
        orderService.updateById(order);

        // 添加日志
        orderLogService.AddSystemLogExit(orderId, "更新订单状态：已签收", userinfoForBack.getUsername());


        return Result.success("已更新订单状态为已签收");
    }


    /**
     * 返回需要售后的订单
     */
    @GetMapping("/getNeedAfterSaleOrder")
    public Result<?> getNeedAfterSaleOrder(@RequestParam(value = "orderNumber", required = false) String orderNumber,
                                           @RequestParam(value = "phone", required = false) String phone,
                                           @RequestParam(value = "pageNo") Integer pageNo,
                                           @RequestParam(value = "pageSize") Integer pageSize
    ) {
        // 查询所有已签收订单
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getOrderStatus, Code.YI_QIAN_SHOU);
        wrapper.eq(StringUtils.hasLength(orderNumber), Order::getOrderNumber, orderNumber);
        wrapper.eq(StringUtils.hasLength(phone), Order::getPhone, phone);
        List<Order> orderList = orderService.list(wrapper);

        // 查询订单日志，获取所有需要售后的订单
        List<OrderDto> orderDtoList = new ArrayList<>();
        for (Order order : orderList) {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(order, orderDto);

            LambdaQueryWrapper<OrderLog> orderLogLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderLogLambdaQueryWrapper.eq(OrderLog::getOrderId, orderDto.getId());
            orderLogLambdaQueryWrapper.orderByDesc(OrderLog::getCreateTime);
            List<OrderLog> orderLogs = orderLogService.list(orderLogLambdaQueryWrapper);

            for (OrderLog orderLog : orderLogs) {
                if (orderLog.getLog().equals(Code.XU_SHOU_HOU)) {
                    orderDto.setOrderLogs(orderLogs);
                    orderDtoList.add(orderDto);
                }
            }

        }


        int fromIndex = (pageNo - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, orderDtoList.size());

        if (fromIndex > orderDtoList.size()) {
            fromIndex = orderDtoList.size();
        }

        List<OrderDto> infoPage = orderDtoList.subList(fromIndex, toIndex);


        // 所有数据 分页返回(获取当前页，每页显示天数，)
//        List<OrderDto> infoPage = new ArrayList<>();
        int total = orderDtoList.size();
//        // 获取当前页(i是索引)
//        for (int i = pageNo; i < pageSize && i < total; i++) {
//            infoPage.add(orderDtoList.get(i));
//        }

        Map<String, Object> data = new HashMap<>();

        data.put("rows", infoPage);
        data.put("total", total);

        return Result.success(data);
    }


    /**
     * 已处理需要售后订单
     */
    @PostMapping("/isOk/{id}")
    public Result<?> isOk(@PathVariable("id") String id) {

        // 删除订单需要售后日志
        LambdaQueryWrapper<OrderLog> logLambdaQueryWrapper = new LambdaQueryWrapper<>();
        logLambdaQueryWrapper.eq(OrderLog::getOrderId, id);

        orderLogService.remove(logLambdaQueryWrapper);

        return Result.success("处理成功");

    }


    /**
     * 获取首页显示信息
     */
    @GetMapping("/getDashboardData")
    public Result<?> dashboardData() {
        Map<String, Integer> data = new HashMap<>();

        // 今天待发货
        LambdaQueryWrapper<Order> sendWrapperOfNow = new LambdaQueryWrapper<>();
        sendWrapperOfNow.eq(Order::getOrderStatus, Code.DAI_FA_HUO);
        // 今天
        LocalDate now = LocalDate.now();
        sendWrapperOfNow.le(Order::getDeliveryDate, now);
        long nowSend = orderService.count(sendWrapperOfNow);
        data.put("withSendOfJingTian", (int) nowSend);  // 今天待发订单

        // 明天待发货(明天日期)
        LambdaQueryWrapper<Order> sendWrapperOfMin = new LambdaQueryWrapper<>();
        sendWrapperOfMin.eq(Order::getOrderStatus, Code.DAI_FA_HUO);
        LocalDate mingtian = LocalDate.of(LocalDate.now().getYear(), LocalDate.now().getMonth(), LocalDate.now().getDayOfMonth() + 1);
        sendWrapperOfMin.eq(Order::getDeliveryDate, mingtian);
        long mingtianFahuo = orderService.count(sendWrapperOfMin);
        data.put("withSendOfMinTian", (int) mingtianFahuo);  // 明天待发订单

        // 后天待发货
        LambdaQueryWrapper<Order> sendWrapperOfHou = new LambdaQueryWrapper<>();
        sendWrapperOfHou.eq(Order::getOrderStatus, Code.DAI_FA_HUO);
        LocalDate houTian = LocalDate.of(LocalDate.now().getYear(), LocalDate.now().getMonth(), LocalDate.now().getDayOfMonth() + 2);
        sendWrapperOfHou.eq(Order::getDeliveryDate, houTian);
        long HouTianFahuo = orderService.count(sendWrapperOfHou);
        data.put("withSendOfHouTian", (int) HouTianFahuo);  // 后天待发订单

        // 预估收货（已寄回订单）今天和明天
        // 今天
        LambdaQueryWrapper<Order> sendBackWrapper = new LambdaQueryWrapper<>();
        sendBackWrapper.eq(Order::getOrderStatus, Code.YI_JI_HUI);
        LocalDate localDate = LocalDate.of(LocalDate.now().getYear(), LocalDate.now().getMonth(), LocalDate.now().getDayOfMonth());
        sendBackWrapper.eq(Order::getGetReceiptDate, localDate);
        long MinTianNum = orderService.count(sendBackWrapper);
        data.put("withSendBackOfJinTian", (int) MinTianNum);

        // 明天
        LambdaQueryWrapper<Order> sendBackWrapperHouTian = new LambdaQueryWrapper<>();
        sendBackWrapperHouTian.eq(Order::getOrderStatus, Code.YI_JI_HUI);
        LocalDate minTian = LocalDate.of(LocalDate.now().getYear(), LocalDate.now().getMonth(), LocalDate.now().getDayOfMonth() + 1);
        sendBackWrapperHouTian.eq(Order::getGetReceiptDate, minTian);
        long minTianNum = orderService.count(sendBackWrapperHouTian);
        data.put("withSendBackOfMinTian", (int) minTianNum);


        // 历史订单信息
        // 已发货
        LambdaQueryWrapper<Order> yiFaHuo = new LambdaQueryWrapper<>();
        yiFaHuo.eq(Order::getOrderStatus, Code.YI_FA_HUO);
        long yiFahuoNum = orderService.count(yiFaHuo);
        data.put("yiFaHuoNum", (int) yiFahuoNum);
        // 已逾期
        LambdaQueryWrapper<Order> yiYuQi = new LambdaQueryWrapper<>();
        yiYuQi.eq(Order::getOrderStatus, Code.YI_YU_QI);
        long yiYuQiNum = orderService.count(yiYuQi);
        data.put("yiYuQiNum", (int) yiYuQiNum);
        // 完结(查询所有完结订单)
        LambdaQueryWrapper<Order> YiWanJie = new LambdaQueryWrapper<>();
        YiWanJie.eq(Order::getOrderStatus, Code.YI_WAN_JIE);
        int YiWanJieNum = 0;
        List<Order> YiWanJieList = orderService.list(YiWanJie);
        YiWanJieNum = YiWanJieList.size();
        data.put("YiWanJieNum", YiWanJieNum);

        // 完结租金金额
        int allMoney = 0;
        for (Order order : YiWanJieList) {
            allMoney += order.getMoney();
        }
        data.put("WanJieMoney", allMoney);

        return Result.success(data);
    }

    /**
     * 批量签收订单
     */
    @PostMapping("/receiveOrders")
    public Result<?> receiveOrders(@RequestBody Map<String, Object> receiveOrders, HttpServletRequest request) {
        List<Map<String, String>> orderIds = (List<Map<String, String>>) receiveOrders.get("orderIds");
        List<String> serialNumbers = (List<String>) receiveOrders.get("serialNumbers");
        String outWarehouseId = (String) receiveOrders.get("outWarehouseId");
        String inWarehouseId = (String) receiveOrders.get("inWarehouseId");

        // 校验数据
        if (orderIds == null || orderIds.size() < 1 || serialNumbers == null || serialNumbers.size() < 1 || outWarehouseId == null || outWarehouseId.equals("") || inWarehouseId == null || inWarehouseId.equals("")) {
            return Result.fail(Code.UPDATE_FAIL_CODE, "数据格式有误");
        }
        String token = Utils.getToken(request);
        User userinfoForBack = userService.getUserinfoForBack(token);

        // 序列号入库, 创建调拨单号
        transferRecordService.TransferGoods(outWarehouseId, inWarehouseId, serialNumbers, token);

        // 设置序列号状态为已入库
        for (String serialNumber : serialNumbers) {
            LambdaQueryWrapper<GoodsSerialNumber> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(GoodsSerialNumber::getSerialNumber, serialNumber);
            GoodsSerialNumber one = goodsSerialNumberService.getOne(wrapper);

            one.setStatus(Code.YI_RU_KU);

            goodsSerialNumberService.updateById(one);
        }


        // 签收订单
        for (Map<String, String> orderIdAdnReceiveId : orderIds) {
            String orderId = orderIdAdnReceiveId.get("orderId");
            String receiveGoodsId = orderIdAdnReceiveId.get("receiveId");

            // 查询订单
            Order order = orderService.getById(orderId);


            // 查询收货信息
            ReceiveGoods receiveGoods = receiveGoodsService.getById(receiveGoodsId);

            // 添加收货运单号
            order.setGetReceiptNumber(receiveGoods.getOddNumber());
            // 添加日志
            if (receiveGoods.getInfo() != null) {
                if (!receiveGoods.getInfo().equals("")) {
                    // 设备状态日志
                    orderLogService.AddUserLog(orderId, receiveGoods.getInfo(), userinfoForBack.getUsername());
                    orderLogService.AddUserLog(orderId, Code.XU_SHOU_HOU, userinfoForBack.getUsername());
                }

            }

            if (receiveGoods.getRemark() != null) {
                if (!receiveGoods.getRemark().equals("")) {
                    // 设备状态日志
                    orderLogService.AddUserLog(orderId, "收货备注：" + receiveGoods.getRemark(), userinfoForBack.getUsername());
                }
            }


            // 设置状态为已签收
            order.setOrderStatus(Code.YI_QIAN_SHOU);
            // 更新订单
            orderService.updateById(order);

            // 添加日志
            orderLogService.AddSystemLogExit(orderId, "更新订单状态：已签收", userinfoForBack.getUsername());

        }

        return Result.success("批量签收成功");
    }
}
